/*
 * @Author: atony2099
 * @Date: 2019-02-14 12:19:34
 * @Last Modified by: atony2099
 * @Last Modified time: 2019-02-15 10:56:28
 */

'use strict';

const Controller = require('egg').Controller;
const _ = require('lodash');

const signValidate = {
  signTime: { type: 'string', trim: 'true', format: /^[0-9]{13}$/ },
};

class SignController extends Controller {
  async index() {
    // 1. validate
    const { body } = this.ctx.request;
    this.ctx.validate(signValidate, body);
    const { signTime } = body;
    let { lastSignDate, continusDay, goldCount, _id } = this.ctx.$userInfo;
    const { sign, user } = this.ctx.service;

    // 2. check if sign
    const currentDate = new Date(Number(signTime));
    if (lastSignDate && currentDate.getTime() < lastSignDate.getTime()) {
      this.ctx.toError(400, 'invaild date');
      return;
    }

    if (lastSignDate) {
      if (this.ctx.helper.isSameDay(currentDate, lastSignDate)) {
        this.ctx.toError(
          400,
          'Sorry, you have signed up today,please sign next day :-D'
        );
        return;
      }
    }
    // 3. create new sign;
    await sign.createNewSign(_id);

    // 4. updateUserinfo
    if (
      lastSignDate &&
      this.ctx.helper.isNearbyDate(lastSignDate, currentDate)
    ) {
      continusDay += 1;
    } else {
      continusDay = 1;
    }

    goldCount = goldCount + 100 + continusDay * 20;
    this.logger.debug(goldCount, 'goldcount====', continusDay);

    const result = await user.updateUserById(_id, {
      goldCount,
      continusDay,
      lastSignDate: currentDate,
    });

    const userInfo = _.pick(result, [
      'username',
      'goldCount',
      'continusDay',
      'lastSignDate',
    ]);

    this.ctx.toSuccess({ userInfo });
  }
}

module.exports = SignController;
